package com.nhjf.mobile.controller.collection;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nhjf.common.page.Pagination;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.model.student.Student;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.ArtPictures;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.model.teachers.UserFollow;
import com.nhjf.pojo.qo.studnet.StudentQo;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.ArtPicturesQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.pojo.qo.teachers.UserFollowQo;
import com.nhjf.service.student.StudentService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.ArtPicturesService;
import com.nhjf.service.teachers.TeachersService;
import com.nhjf.service.teachers.UserFollowService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/userAttention")
public class UserAttentionController {

	@Autowired
	private UserService userService;

	@Autowired
	private AdminSessionService adminSessionService;

	@Autowired
	private UserFollowService userFollowService;
	@Autowired
	private ArtPicturesService artPicturesService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private TeachersService teacherService;


	/**
	 * 
	 * 关注别人
	 * @param request
	 * @param response
	 * @param model
	 * @param token
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userAttention_show")
	public String shouAttention(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="token", required=true)String  token,String userId) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession==null) {
				resMap.put("code", "406");
				resMap.put("message", "不存在此账号！");
				return JSONObject.fromObject(resMap).toString();
			}else {
				UserQo userQo=new UserQo();
				userQo.setSeachRole(true);
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user==null) {
					resMap.put("code", "406");
					resMap.put("message", "未登录!");
					return JSONObject.fromObject(resMap).toString();
				}else {
					UserQo userQo1=new UserQo();
					userQo1.setSeachRole(true);
					userQo1.setUserId(Long.parseLong(userId));
					User user2= userService.queryUnique(userQo1);
					UserFollowQo userFollowQo=new UserFollowQo();
					userFollowQo.setFansUserId(user.getId());
					userFollowQo.setFollowUserId(user2.getId());
					UserFollow follow1= userFollowService.queryUnique(userFollowQo);
					if(Integer.parseInt(userId)==user.getId()) {
						resMap.put("code", "500");
						resMap.put("message", "不能关注自己!");
						//						User user3 =new User();
						return JSONObject.fromObject(resMap).toString();
					}
					if(follow1!=null) {
						resMap.put("code", "506");
						resMap.put("message", "已经关注!");
						return JSONObject.fromObject(resMap).toString();
					}

					if(user.getFollow()!=null && user.getFollow()>0) {
						user.setFollow(user.getFollow()+1);
					}else {
						user.setFollow(1);
					}
					if(user2.getFans()!=null && user2.getFans()>0) {
						user2.setFans(user2.getFans()+1);
					}else {
						user2.setFans(1);
					}


					//增加粉丝数量+1
					userService.update(user);
					//增加关注人数量+1
					userService.update(user2);
					UserFollow follow=new UserFollow();
					follow.setFansUser(user);
					follow.setFollowUser(user2);
					if(user.getIsRole()!=1) {
						if(user2.getIsRole()!=1) {
							follow.setType(3);//3代表机构管理员
							follow.setFollowTime(new Date());
							userFollowService.save(follow);
							resMap.put("code", "200");
							resMap.put("message", "成功!");
							return JSONObject.fromObject(resMap).toString();
						}else {
							follow.setType(2);//2代表老师关注学生
							follow.setFollowTime(new Date());
							userFollowService.save(follow);
							resMap.put("code", "200");
							resMap.put("message", "成功!");
							return JSONObject.fromObject(resMap).toString();
						}
					}else {
						if(user2.getIsRole()!=1) {
							follow.setType(4);//4代表学生关注学生
							follow.setFollowTime(new Date());
							userFollowService.save(follow);
							resMap.put("code", "200");
							resMap.put("message", "成功!");
							return JSONObject.fromObject(resMap).toString();
						}else {
							follow.setType(1);//1代表学生关注老师
							follow.setFollowTime(new Date());
							userFollowService.save(follow);
							resMap.put("code", "200");
							resMap.put("message", "成功!");
							return JSONObject.fromObject(resMap).toString();
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "失败!");
			return JSONObject.fromObject(resMap).toString();
		}
	}
	/**
	 * 查看已关注的人
	 * @param request
	 * @param response
	 * @param model
	 * @param token
	 * @param followUserId
	 * @param page
	 * @return
	 */
	@RequestMapping("/userAttention_showFollow")
	@ResponseBody
	public String showFollow(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="token", required=false)String  token, String followUserId,@RequestParam(value = "page", defaultValue = "1")Integer page) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {

					UserFollowQo followQo=new UserFollowQo();
					followQo.setSeachFansUser(true);
					followQo.setSeachFollowUser(true);
					followQo.setFansUserId(Long.parseLong(followUserId));
					Pagination pagination = new Pagination();
					pagination.setPageSize(10);
					pagination.setPageNo(page);
					pagination.setCondition(followQo);
					pagination = userFollowService.queryPagination(pagination);
					List<UserFollow> userFollowList=(List<UserFollow>)pagination.getList();
					for (UserFollow userFollow : userFollowList) {
						if(userFollow.getFansUser()!=null && userFollow.getFollowUser()!=null) {
							userFollow.getFansUser().setUserPassword("");
							userFollow.getFollowUser().setUserPassword("");
						}
						ArtPicturesQo artPicturesQo=new ArtPicturesQo();
						artPicturesQo.setUserId(userFollow.getFollowUser().getId());
						int artCount= artPicturesService.queryCount(artPicturesQo);
						userFollow.getFollowUser().setArtPicturesNum(artCount);
						SysProperties sysProperties=SysProperties.getInstance();
						String imagePath=sysProperties.get("imagePath");
						if(userFollow.getFollowUser().getIsRole()==2) {
							StudentQo studentQo=new StudentQo();
							studentQo.setUserid(userFollow.getFollowUser().getId());
							Student student= studentService.queryUnique(studentQo);
							
							if(student!=null) {
								userFollow.getFollowUser().setNickName(student.getNickname());
								if(!StringUtils.isEmpty(student.getAvatar())) {
									if(student.getAvatar().indexOf(imagePath+"/picture/")>=0) {

									}else {
										userFollow.getFollowUser().setAvatar(imagePath+"/picture/"+student.getAvatar());
									}
								}
							}	
						}else {
							TeachersQo teachersQo=new TeachersQo();
							teachersQo.setUserId(userFollow.getFollowUser().getId());
							Teacher teacher= teacherService.queryUnique(teachersQo);
							if(teacher!=null) {
								userFollow.getFollowUser().setNickName(teacher.getNickname());
								if(!StringUtils.isEmpty(teacher.getAvatar())) {
									if(teacher.getAvatar().indexOf(imagePath+"/picture/")>=0) {

									}else {
										userFollow.getFollowUser().setAvatar(imagePath+"/picture/"+teacher.getAvatar());
									}
								}
							}
						}
					}

					if(userFollowList!=null) {
						pagination.setList(userFollowList);
						resMap.put("code", "200");
						resMap.put("message", pagination);
						return JSONObject.fromObject(resMap).toString();
					}else {
						resMap.put("code", "404");
						resMap.put("message", "暂无关注");
						return JSONObject.fromObject(resMap).toString();
					}
				
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常！");
			return JSONObject.fromObject(resMap).toString();
		}


	}

	/**
	 * 用户取消关注
	 * @param request
	 * @param response
	 * @param model
	 * @param token
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userAttention_del")
	public String delAttention(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="token", required=true)String  token,String followUserId) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession==null) {
				resMap.put("code", "406");
				resMap.put("message", "不存在此账号！");
				return JSONObject.fromObject(resMap).toString();
			}else {
				UserQo userQo=new UserQo();
				userQo.setSeachRole(true);
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user==null) {
					resMap.put("code", "406");
					resMap.put("message", "未登录!");
					return JSONObject.fromObject(resMap).toString();
				}else {
					UserFollowQo followQo=new UserFollowQo();
					followQo.setSeachFansUser(true);
					followQo.setSeachFollowUser(true);
					followQo.setFansUserId(user.getId());
					followQo.setFollowUserId(Long.parseLong(followUserId));
					UserFollow userFollow=userFollowService.queryUnique(followQo);  //找到id进行修改
					if(userFollow==null) {
						resMap.put("code", "500");
						resMap.put("message", "未关注此用户!");
						return JSONObject.fromObject(resMap).toString();
					}
					UserQo userQo2=new UserQo();
					userQo2.setUserId(userFollow.getFollowUser().getId());
					userQo2.setSeachRole(true);
					User user2= userService.queryUnique(userQo2);
					if(user2.getFans()!=null && user2.getFans()>0) {
						//减少粉丝数量-1
						user2.setFans(user2.getFans()-1);
						userService.update(user2);
					}else {
						resMap.put("code", "404");
						resMap.put("message", "粉丝为0!");
						return JSONObject.fromObject(resMap).toString();
					}
					if(user.getFollow()!=null &&user.getFollow()>0) {
						//减少关注人数量-1
						user.setFollow(user.getFollow()-1);
						userService.update(user);
					}else {
						resMap.put("code", "404");
						resMap.put("message", "粉丝为0!");
						return JSONObject.fromObject(resMap).toString();
					}
					userFollowService.deleteById(userFollow.getId());
					resMap.put("code", "200");
					resMap.put("message", "成功!");
					return JSONObject.fromObject(resMap).toString();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "失败!");
			return JSONObject.fromObject(resMap).toString();
		}
	}
	/**
	 * 查看当前登陆用户全部粉丝
	 * @param request
	 * @param response
	 * @param model
	 * @param token
	 * @param fansUserId
	 * @param page
	 * @return
	 */
	@RequestMapping("/userAttention_showFans")
	@ResponseBody
	public String showFans(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="token", required=false)String  token, String fansUserId,@RequestParam(value = "page", defaultValue = "1")Integer page) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
					UserFollowQo userFollowQo=new UserFollowQo();
					userFollowQo.setSeachFansUser(true);
					userFollowQo.setSeachFollowUser(true);
					userFollowQo.setFollowUserId(Long.parseLong(fansUserId));  
					Pagination pagination = new Pagination();
					pagination.setPageSize(10);
					pagination.setPageNo(page);
					pagination.setCondition(userFollowQo);
					pagination = userFollowService.queryPagination(pagination);
					List<UserFollow> userFansList=(List<UserFollow>)pagination.getList();
					for (UserFollow userFollow : userFansList) {
						if(userFollow.getFansUser()!=null && userFollow.getFollowUser()!=null) {
							userFollow.getFansUser().setUserPassword("");
							userFollow.getFollowUser().setUserPassword("");
						}
						ArtPicturesQo artPicturesQo=new ArtPicturesQo();
						artPicturesQo.setUserId(userFollow.getFansUser().getId());
						int artCount= artPicturesService.queryCount(artPicturesQo);
						userFollow.getFansUser().setArtPicturesNum(artCount);
						SysProperties sysProperties=SysProperties.getInstance();
						String imagePath=sysProperties.get("imagePath");
						if(userFollow.getFansUser().getIsRole()==2) {
							StudentQo studentQo=new StudentQo();
							studentQo.setUserid(userFollow.getFansUser().getId());
							Student student= studentService.queryUnique(studentQo);
							
							if(student!=null) {
								userFollow.getFansUser().setNickName(student.getNickname());
								if(!StringUtils.isEmpty(student.getAvatar())) {
									if(student.getAvatar().indexOf(imagePath+"/picture/")>=0) {

									}else {
										userFollow.getFansUser().setAvatar(imagePath+"/picture/"+student.getAvatar());
									}
								}
							}	
						}else {
							TeachersQo teachersQo=new TeachersQo();
							teachersQo.setUserId(userFollow.getFansUser().getId());
							Teacher teacher= teacherService.queryUnique(teachersQo);
							if(teacher!=null) {
								userFollow.getFansUser().setNickName(teacher.getNickname());
								if(!StringUtils.isEmpty(teacher.getAvatar())) {
									if(teacher.getAvatar().indexOf(imagePath+"/picture/")>=0) {

									}else {
										userFollow.getFansUser().setAvatar(imagePath+"/picture/"+teacher.getAvatar());
									}
								}
							}
						}
					}
					if(userFansList!=null) {
						pagination.setList(userFansList);
						resMap.put("code", "200");
						resMap.put("message", pagination);
						return JSONObject.fromObject(resMap).toString();
					}else {
						resMap.put("code", "404");
						resMap.put("message", "暂无粉丝");
						return JSONObject.fromObject(resMap).toString();
					}
				
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常！");
			return JSONObject.fromObject(resMap).toString();
		}
	}
	/**
	 * 查询是否已经关注
	 * @param request
	 * @param response
	 * @param model
	 * @param token
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userAttention_isGz")
	public String isGzAttention(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(value="token", required=true)String  token,String userId) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession==null) {
				resMap.put("code", "406");
				resMap.put("message", "不存在此账号！");
				return JSONObject.fromObject(resMap).toString();
			}else {
				UserQo userQo=new UserQo();
				userQo.setSeachRole(true);
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user==null) {
					resMap.put("code", "406");
					resMap.put("message", "未登录!");
					return JSONObject.fromObject(resMap).toString();
				}else {
					UserQo userQo1=new UserQo();
					userQo1.setSeachRole(true);
					userQo1.setUserId(Long.parseLong(userId));
					User user2= userService.queryUnique(userQo1);
					UserFollowQo userFollowQo=new UserFollowQo();
					userFollowQo.setFansUserId(user.getId());
					userFollowQo.setFollowUserId(user2.getId());
					UserFollow follow1= userFollowService.queryUnique(userFollowQo);
					if(follow1!=null) {
						resMap.put("code", "200");
						resMap.put("message", "已经关注!");
						return JSONObject.fromObject(resMap).toString();
					}else {
						resMap.put("code", "506");
						resMap.put("message", "未关注!");
						return JSONObject.fromObject(resMap).toString();
					}

				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "查询失败!");
			return JSONObject.fromObject(resMap).toString();
		}
	}
}
